package com.zeedev.flyingsaucer.beers.downloaders;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.widget.Toast;
import com.google.inject.Inject;
import mobi.zeedev.flyingsaucer.common.DataModule.FlyingSaucerConv;
import mobi.zeedev.flyingsaucer.common.DataModule.MetaBeer;
import mobi.zeedev.flyingsaucer.common.DataModule.Util;
import mobi.zeedev.flyingsaucer.common.WebLinkModule.impl.IndividualBeerQueryImpl;
import roboguice.inject.InjectExtra;
import roboguice.util.Ln;
import roboguice.util.RoboAsyncTask;

/**
 * User: James
 * Date: 1/1/11
 * Time: 11:29 PM
 */
public class BeerDownloader extends RoboAsyncTask<ContentValues> {

    @InjectExtra(MetaBeer.BEER_ID)
    Integer beerId;

    @Inject
    IndividualBeerQueryImpl individualBeerQueryImpl;

    @Inject
    Activity mActivity;

    @Inject
    ContentResolver mContentResolver;

    @Inject
    Context mContext;

    @Override
    public ContentValues call() throws Exception {
        ContentValues ret = null;
        ret = individualBeerQueryImpl.getContentValue(beerId);
        return ret;
    }


    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return super.cancel(mayInterruptIfRunning);
    }

    @Override
    protected void onException(Exception e) throws RuntimeException {
        super.onException(e);
        Ln.e("There was an error downloading an individual beer." + beerId, e);
        Toast.makeText(mContext, "There was an error getting your beer's information.  Please try again.", Toast.LENGTH_SHORT).show();
        mActivity.finish();
    }

    @Override
    protected void onFinally() throws RuntimeException {
        super.onFinally();
    }

    @Override
    protected void onInterrupted(InterruptedException e) {
        super.onInterrupted(e);
    }

    @Override
    protected void onPreExecute() throws Exception {
        super.onPreExecute();
    }


    @Override
    protected void onSuccess(ContentValues result) throws Exception {
        super.onSuccess(result);
        if (result != null) {
            int res = mContentResolver.update(FlyingSaucerConv.Beers.CONTENT_URI, result, FlyingSaucerConv.Beers.BEER_ID + "=?", Util.asAr(result.getAsString(FlyingSaucerConv.Beers.BEER_ID)));
        } else {
            Toast.makeText(mContext, "There was an error getting the beer information.", Toast.LENGTH_SHORT).show();
        }
    }


}
